import { useMemo, useState } from 'react';
import styles from './style.module.scss';
import { Input, Select } from 'antd';

const CONST_OTHER = "OTHER";

const IdentityDate = ({ value, onChange }: { value: string, onChange: (value?: string) => void  }) => {
    const [ startDate, setStartDate ] = useState(value ? value.split('-')[0] : null);
    const [ endDate, setEndDate ] = useState(value ? value.split('-')[1] : null);
    const [ displayValue, setDisplayValue ] = useState(value);
    const startDateList = useMemo(() => {
        const optionList = ",".repeat(20).split(",").map((_,index) =>({
            label: `${index + 2010}年`,
            value: `${index + 2010}`
        }));
        optionList.push({ label: "无认定期限", value: "无"});
        optionList.push({ label: "其他", value: CONST_OTHER });
        return optionList;
    }, [startDate]);
    const endDateList = useMemo(() => {
        return ",".repeat(20).split(",").map((_,index) =>({
            label: `${index + 2010}年`,
            value: `${index + 2010}`
        })).filter((v) => startDate && /^[\d]+$/.test(startDate || "") && parseInt(v.value) > parseInt(startDate));
    }, [startDate]);
    return (<><div className={styles.visisteDateTime}>
        <section className={styles.visisteDateTimeSelect}>
            <Select options={startDateList} value={startDate} placeholder="请选择开始时间" onChange={(value) => {
                setStartDate(value);
                setEndDate(null);
                setDisplayValue('');
                if(value !== CONST_OTHER) {
                    typeof onChange === "function" && onChange(value === "无" ? "无" : undefined);
                }
            }}/>
        </section>
        { startDate && /^[\d]+$/.test(startDate) && <section className={styles.visisteDateTimeInput}>
            <Select options={endDateList} value={endDate} placeholder="请选择结束时间" onChange={(value) => {
                setEndDate(value);
                setDisplayValue(`${startDate}-${value}`);
                typeof onChange === "function" && onChange(`${startDate}-${value}`);
            }}/>
        </section> }
        { startDate === CONST_OTHER && <section className={styles.visisteDateTimeInput}>
            <Input type="text" placeholder="请输入时间段"
                onChange={(event: React.ChangeEvent<HTMLInputElement>) => {
                    setDisplayValue(event.target.value);
                    typeof onChange === "function" && onChange(event.target.value);
                }} />
            </section>
        }
    </div>
    <label style={{display: "block", padding: "5px 0"}} >认证期限：{displayValue}</label>
    </>)
};

export default IdentityDate;
